<?php

class EventsController extends Admin_Controller {

    const NO_ERRORS = 0x00;
    const ERROR_FILE_TYPE = 0x01;
    const ERROR_EXCHANGE_FILE = 0x02;
    const UPLOAD_ERROR = 0x03;
    const DB_ERROR = 0x04;
    const ERROR_COMPARE_KOATUU = 0x05;
    
    const STATUS_NEED_FOR_CHECK = 1;
    const STATUS_CHECKED = 2;
    const STATUS_REJECTED = 3;
    
    const ADMIN_USER = 1;
    const CENTER_USER = 12;
    
   
  
     public function init() {
        parent::init();
        $this->setActiveCat(990);
        $this->_table = new Admin_Table_Motohelp_Events();

    }

    public function indexAction() {
        
        
        $form = new Llib_Form($this->_request);
        $filters = array();

        if ($this->_request->isPost()) {
            $filters['by_date'] = $this->_request->getParam('by_date', '');
            $filters['from_date'] = $this->_request->getParam('from_date', '');
            $filters['to_date'] = $this->_request->getParam('to_date', '');
            $filters['by_region'] = $this->_getParam('by_region', '');
            $filters['by_district'] = $this->_getParam('by_district', '');
            $filters['by_town'] = $this->_getParam('by_town', '');
            $filters['by_status'] = $this->_request->getParam('by_status', '');
        }

        $filters = $this->SessionVarsEx($filters, array('by_date', 'from_date', 'to_date', 'by_region' => 0, 'by_district' => 0, 'by_town' => 0,'by_status' => 0), $this->_request->getParam('reset', false));

        $id_region = $filters['by_region'];
        $id_district = $filters['by_district'];
        $id_town = $filters['by_town'];

//        $filters['id_region'] = $this->_table->addressGetRegions($id_region);
//        $filters['id_district'] = $this->_table->addressGetDistricts($id_region, $id_district);
//        $filters['id_town'] = $this->_table->addressGetTowns($id_region, $id_district, $id_town);
//        $filters['id_status'] = $this->_table_lots->GetStatusList($filters['by_status']);
//        array_splice($filters['id_status'], 3);

        $form->AddData($filters);

        if (isset($this->_user->koatuu) && $this->_user->koatuu != 0 ) $filters['koatuu']=$this->_user->koatuu;
        
        $lclm = new Llib_List($this->_request, $this->_sess);
        $lclm->AddParams(array(
            //'checkboxes' => true,
            'link' => "/" . $this->controller . "/edit/"//"/lots/"
        ));
        $lclm->AddColumn('№', 'id', array('width' => '10%', 'sort' => 1));
        $lclm->AddColumn('Дата', 'event_date', array('width' => '20%', 'sort' => 1));
        $lclm->AddColumn('Описание', 'short_descr', array('width' => '35%', 'sort' => 1));
        $lclm->AddColumn('Местоположение', 'place', array('width' => '35%', 'sort' => 1));

        $lclm->AddData($this->_table->getDataList($lclm->page, $lclm->s, $lclm->pager_count, $filters));
        

        $this->startContent();
        $this->view->xmlWriter->startElement("Main");
        $this->view->assign('List', $lclm->GetList());
        $this->view->assign($form->GetFrom());
        $this->view->xmlWriter->endElement();
        $this->view->xmlWriter->endElement();
    }
    
//    public function addAction()
//    {
//    	$form = new Llib_Form($this->_request);
//
//        $d = array();
//    	if ($this->_request->isPost()) 
//        {
//			$d = $form->GetPostedData();
//        	if($id = $this->_table->insert($d, $this->_user->id)) 
//        	{
//        		$d = array();
//        		$form->SetSuccess();        	
//        	}
//        	else $form->SetError($this->_table->GetError());        	
//        } 
//        
//        $id_event_type = @$d['id_event_type'];
//        $id_region = @$d['id_region'];
//        $id_district = @$d['id_district'];
//        
//        //if(!($id_country > 0)) $id_country = -1;
//
//        $d['id_type_event'] = $this->_table->GetEventTypeList($id_event_type);
//
//        $form->AddData($d);       
//
//    	$this->startContent();
//	        $this->view->xmlWriter->startElement("Main");
//	        $this->view->assign('Title', 'Добавить проишествие');
//	        $this->view->assign($form->GetFrom());
//		    $this->view->xmlWriter->endElement();
//	    $this->view->xmlWriter->endElement();
//    }
     
    public function lotListAction(){
        $filters = array();
        if ($this->_request->isPost()) {
        	$filters['by_cad_num'] = $this->_request->getParam('by_cad_num', '');
        	$filters['by_status'] = $this->_request->getParam('by_status', '');
                $filters['by_approved'] = $this->_request->getParam('by_approved', '');
                $filters['by_gone'] = $this->_request->getParam('by_gone', '');
        }

        $filters = $this->SessionVarsEx($filters, array('by_cad_num','by_status','by_approved' => '-1','by_gone' => '-1'), $this->_request->getParam('reset', false));
        $error = intval($this->_request->getParam('error'));       

        $form = new Llib_Form($this->_request);

        if ($error) {
            switch ($error) {
                case AuctionController::ERROR_EXCHANGE_FILE:
                    $form->SetError("Обмінний файл містить помилки.");
                    break;
                case AuctionController::ERROR_FILE_TYPE:
                    $form->SetError("Не вірний формат файлу.");
                    break;
                case AuctionController::UPLOAD_ERROR:
                    $form->SetError("Виникла помилка під час завантаження обмінного файлу.");
                    break;
                case AuctionController::DB_ERROR:
                    $form->SetError("Не вдалося створити лот. Виникла помилка бази даних.");
                    break;
                case AuctionController::ERROR_COMPARE_KOATUU:
                    $form->SetError("Не вдалося створити лот. КОАТУУ лота не знаходиться у районі корістувача.");
                    break;
                default:
                    $form->SetError("Виникла помилка під час створення лоту.");
                    break;
            }
        }

        if (isset($this->_user->koatuu) && $this->_user->koatuu != 0 ) $filters['cad_num_koatuu']=$this->_user->koatuu;
        $filters['id_status'] = $this->_table_lots->GetStatusList($filters['by_status']);
        $filters['is_approved'] = $this->_table_lots->GetApprovedList($filters['by_approved']);
        $filters['is_gone'] = $this->_table_lots->GetGoneList($filters['by_gone']);

        $form->AddData($filters);

        $lclm = new Llib_List($this->_request, $this->_sess);
        $lclm->AddParams(array(
            'checkboxes' => true,
        	//'link_fields'=>array('cad_num'),
            'link' => "/" . $this->controller . "/view-lot/id-lot/"
        ));
        $lclm->AddColumn('№ Лоту', 'id', array('width' => '5%', 'sort' => 1));
        $lclm->AddColumn('Кадастровий номер', 'cad_num', array('width' => '10%', 'sort' => 1));
        $lclm->AddColumn('Площа (га)', 'area', array('width' => '5%', 'sort' => 1));
        $lclm->AddColumn('Адреса', 'parcel_address', array('width' => '30%', 'sort' => 1));
        $lclm->AddColumn('Вид цільового призначення земель (згідно класифікатору)', 'purpose', array('width' => '30%', 'sort' => 0));
        $lclm->AddColumn('', 'attantion', array('width' => '1%', 'sort' => 0));  
        $lclm->AddColumn('Статус', 'status', array('width' => '20%', 'sort' => 1));
        $lclm->AddColumn('', 'is_published', array('width' => '1%', 'sort' => 1));
        $data = $this->_table_lots->getDataList($lclm->page, $lclm->s, $lclm->pager_count, $filters);
        $lclm->AddData($data);
//  print_r($data);
//exit();
        $this->startContent();
        $this->view->xmlWriter->startElement("Main");
        $this->view->assign('List', $lclm->GetList());
        $this->view->assign($form->GetFrom());
        $this->view->xmlWriter->endElement();
        $this->view->xmlWriter->endElement();
    }

    
    public function editAction() {       
        $id = $this->_request->getParam('id');

        if (!($id > 0)) $this->_redirect('/error/e404');

        $saveexit = $this->_getParam('saveexit');
        $form = new Llib_Form($this->_request);

        if ($this->_request->isPost()) {
            $posted_data = $form->GetPostedData();
            (!isset($posted_data['is_200']))?$posted_data['is_200'] = 0:true;
            (!isset($posted_data['is_300']))?$posted_data['is_300'] = 0:true;
                    if ($this->_table->update($posted_data, $id, $this->_user->id)) {
                        if (!is_null($saveexit)) $this->_redirect("/" . $this->controller);
                        $form->SetSuccess();
                    } else $form->SetError($this->_table->GetError());
            
        }
        $data = $this->_table->getDataRow($id);

        $id_type_event = intval(@$data['id_type_event']);
        $district_id = intval(@$data['district_id']);
        $reaction_type_id = intval(@$data['reaction_type_id']);

        $data['id_type_event'] = $this->_table->GetEventTypeList($id_type_event);
        $data['district_id'] = $this->_table->GetDistrictKievList($district_id);
        $data['reaction_type_id'] = $this->_table->GetReactionTypeList($reaction_type_id);

//        if($data['id_status']>0 && $data['id_status']!=3 && $this->_user->role_id != AuctionController::CENTER_USER) 
//            $this->_redirect('/'.$this->controller.'/view/'.$id);
        
        $form->AddData($data);

        $this->startContent();
        $this->view->xmlWriter->startElement("Main");
        $this->view->xmlWriter->writeAttribute('id', $id);
        $this->view->assign($form->GetFrom());
        $this->view->xmlWriter->endElement();
        $this->view->xmlWriter->endElement();
    }

    
    
    
  
     public function viewAction() {
          //$this->_table2 = new Admin_Table_Auction_AuctionExecuters();   
           //$this->table_cities = new Admin_Table_Auction_Cities();
        
          
            
           
        
        $id = $this->_request->getParam('id');
        if (!($id > 0)) $this->_redirect('/error/e404');
        $form = new Llib_Form($this->_request);

        
//        if ($this->_request->isPost()) {
//            $posted_data = $form->GetPostedData();
//
//            if(!empty($posted_data)){
//                 if(isset($posted_data['var'])){
//                        unset (  $posted_data['var']);
//                        $form->SetSuccess("Змінено."); 
//                        $df = new Admin_Table_Auctionview();
//
//                        $df->newupdate($posted_data,$id,$this->_user->id);        
//                        $this->_redirect("/" . $this->controller."/" .$this->action ."/".$id);           
//                      
//                   }elseif(isset($posted_data['id_status_reason']) or  isset($posted_data['reject_reason'] ) ){
//                        //-----------------
//                        if(isset($posted_data['id_status'])){
//                                unset($posted_data['id']);
//                                if ($this->_table->update($posted_data, $id, $this->_user->id, $this->_user->role_id)) {
//                                        $form->SetSuccess("Статус успішно змінено.");
//                                }else $form->SetError("Ви не можете повернути матеріал у зв'язку з тим, що його було вже опубліковно");
//                        }else $form->SetError("Ви не змінили статус.");
//                        //-----------------
//                    }
//            }
//         }      
        
        $data = $this->_table->getAuctionInfo($id);  
        $data2 = $this->_table->GetDataRow($id);
  
        if(empty($data2['activity'])) 
            unset($data2['activity']);
        $id_region = intval(@$data2['id_region']);
        $id_district = intval(@$data2['id_district']);
        $id_city = intval(@$data2['id_city']);

        $df = new Admin_Table_Auctionview();

        $data2['id_region']  = $df->GetRegionsList($id_region,$this->_user->id);
        $data2['id_district']= $this->table_cities->GetDistrictsList($id_district, $id_region);
        $data2['id_city'] = $this->table_cities->GetCitiesList($id_city, $id_region, $id_district);        
         
        $data = array_merge($data, $this->_table->getAuctionLotsCount($id));
        $data = array_merge($data, $data2);
        
        if($data['id_status']==AuctionController::STATUS_REJECTED) $form->SetError("Повернуто з причиною: ".$data['reject_reason']);
        //первый параметр устанавливает оператора для выборки списка возможных статусов        
        $data['status_list'] = $this->_table->GetStatusListForChange(0, @$data['id_status']);
        array_splice($data['status_list'], 3);
        

        $form->AddData($data);  
    	$this->startContent();
	        $this->view->xmlWriter->startElement("Main");
                        $this->view->xmlWriter->writeAttribute('id', $id);
	        $this->view->assign('Title', 'Редагувати');
	        $this->view->assign($form->GetFrom());
		    $this->view->xmlWriter->endElement();
	    $this->view->xmlWriter->endElement();
  
   }
     
    
    
    //------------------------- end  -----------------------------------------------

    public function lotsAction() {
        $id = $this->_request->getParam('id');
        if ($id==0) $this->_redirect('/'.$this->controller.'/lot-list');
        if (!($id > 0)) $this->_redirect('/error/e404');

        $filters = array();

        if ($this->_request->isPost()) {
            $filters['by_cad_num'] = $this->_request->getParam('by_cad_num', '');
            $filters['by_status'] = $this->_request->getParam('by_status', '');
            $filters['by_approved'] = $this->_request->getParam('by_approved', '');
            $filters['by_gone'] = $this->_request->getParam('by_gone', '');
        }

        $filters = $this->SessionVarsEx($filters, array('by_cad_num','by_status','by_approved' => '-1','by_gone' => '-1'), $this->_request->getParam('reset', false));
        $error = intval($this->_request->getParam('error'));

        $form = new Llib_Form($this->_request);

        if ($error) {
            switch ($error) {
                case AuctionController::ERROR_EXCHANGE_FILE:
                    $form->SetError("Обмінний файл містить помилки.");
                    break;
                case AuctionController::ERROR_FILE_TYPE:
                    $form->SetError("Не вірний формат файлу.");
                    break;
                case AuctionController::UPLOAD_ERROR:
                    $form->SetError("Виникла помилка під час завантаження обмінного файлу.");
                    break;
                case AuctionController::DB_ERROR:
                    $form->SetError("Не вдалося створити лот. Виникла помилка бази даних.");
                    break;
                case AuctionController::ERROR_COMPARE_KOATUU:
                    $form->SetError("Не вдалося створити лот. КОАТУУ лота не знаходиться у районі корістувача.");
                    break;
                default:
                    $form->SetError("Виникла помилка під час створення лоту.");
                    break;
            }
        }
        $filters = array_merge($filters, $this->_table->getAuctionLotsCount($id));
        
        $filters['id_auction'] = $id;
        //$filters['role_id'] = $this->_user->role_id;
        if (isset($this->_user->koatuu) && $this->_user->koatuu != 0 ) $filters['cad_num_koatuu']=$this->_user->koatuu;
        $filters['id_status'] = $this->_table_lots->GetStatusList($filters['by_status']);
        $filters['is_approved'] = $this->_table_lots->GetApprovedList($filters['by_approved']);
        $filters['is_gone'] = $this->_table_lots->GetGoneList($filters['by_gone']);
        
        $lclm = new Llib_List($this->_request, $this->_sess);
        $lclm->AddParams(array(
            'checkboxes' => true,
        	//'link_fields'=>array('cad_num'),
            'link' => "/" . $this->controller . "/view-lot/" . $id . "/id-lot/"//"/file-attache/" . $id . "/id-lot/"
        ));
        $lclm->AddColumn('Кадастровий номер', 'cad_num', array('width' => '10%', 'sort' => 1));
        $lclm->AddColumn('Площа (га)', 'area', array('width' => '5%', 'sort' => 1));
        $lclm->AddColumn('Адреса', 'parcel_address', array('width' => '27%', 'sort' => 1));
        $lclm->AddColumn('Вид цільового призначення земель (згідно класифікатору)', 'purpose', array('width' => '28%', 'sort' => 0));
        $lclm->AddColumn('', 'attantion', array('width' => '1%', 'sort' => 0));  
        $lclm->AddColumn('Статус', 'status', array('width' => '25%', 'sort' => 1));
        $lclm->AddData($this->_table_lots->getDataList(/*$id, */$lclm->page, $lclm->s, $lclm->pager_count, $filters));
        $filters['auction_status'] = $this->_table->getStatus($id);
        $form->AddData($filters);

        $this->startContent();
        $this->view->xmlWriter->startElement("Main");
        $this->view->xmlWriter->writeAttribute('id', $id);
        $this->view->assign('List', $lclm->GetList());
        $this->view->assign($form->GetFrom());
        $this->view->xmlWriter->endElement();
        $this->view->xmlWriter->endElement();
    }

    public function addLotAction() {
        $id = $this->_request->getParam('id');
        if (!($id > 0)) $this->_redirect('/error/e404');

        $has_error = AuctionController::NO_ERRORS;
        $form = new Llib_Form($this->_request);

        if ($this->_request->isPost()) {
            $posted_data = $form->GetPostedData();

            if (!empty($posted_data)) {
                $adapter = $this->getFileAdapterAll();
                $files = $adapter->getFileInfo();

                foreach ($files as $file => $info) {
                    if ($adapter->isUploaded($file) && $adapter->isValid($file)) {
                        if ($info['type'] == "application/xml") {
                            $xml = new Llib_Xml($info['tmp_name']);
                            $koatuu = 0;

                            if (!$xml->hasErrors()) {
                                $parcel_info = $xml->getParcelInfo();

                                $data = array(); // LOTS
                                
                              
                                $data['id_auction'] = $id;
                                $data['name'] = $info['name'];
                                $cad_num = $xml->getCadastralNumber();
                                $data['cad_num_koatuu'] = $cad_num['KOATUU'];
                                $data['cad_num_zone'] = $cad_num['CadastralZoneNumber'];
                                $data['cad_num_quarter'] = $cad_num['CadastralQuarterNumber'];
                                $data['cad_num_parcel'] = $cad_num['ParcelID'];
                                $data['area'] = $parcel_info['ParcelMetricInfo']['Area']['Size'];
                                $data['address'] = $parcel_info['ParcelLocationInfo']['FullAddress'];
                                $data['purpose'] = $parcel_info['CategoryPurposeInfo']['Purpose'];

                            	if (!empty($parcel_info['ValuationInfo'])) {
                                    $data['start_price'] = @$parcel_info['ValuationInfo'][0]['Value'];
                                    if (preg_match("/^\d+\.\d$/ui", $data['start_price'])) {
                                        $data['start_price'] .= "0";
                                    }
                                }
                                
                                $filter_koatuu = substr($data['cad_num_koatuu'], 0, 5);
                                $user_koatuu = substr(str_pad($this->_user->koatuu, 10, '0', STR_PAD_LEFT), 0, 5);
//                                var_dump($filter_koatuu);
//                                echo '   ';
//                                var_dump($user_koatuu);die();
                                if($filter_koatuu == $user_koatuu || $this->_user->role_id == AuctionController::ADMIN_USER || $this->_user->role_id == AuctionController::CENTER_USER){
                                    
                                    $koatuu = substr($data['cad_num_koatuu'], 0, 2);

                                    $lot_id = $this->_table_lots->insert($data, $this->_user->id);

                                    if ($lot_id) {
                                        $data = array(); // EXCHANGE_FILE
                                        $data['name'] = $info['name'];
                                        $data['id_lot'] = $lot_id;

                                        $table_exchange_file = new Admin_Table_Auction_ExchangeFile();
                                        $file_id = $table_exchange_file->insert($data, $this->_user->id);

                                        if ($file_id) {
                                            $path = $this->controller . DIRECTORY_SEPARATOR . $koatuu . DIRECTORY_SEPARATOR . intval($file_id / 1000000) . DIRECTORY_SEPARATOR . intval($file_id / 1000);

                                            if ($this->_files->CreateFolderRecursive($path)) {
                                                $ext = pathinfo($info['name']);
                                                $file_name = $file_id . "." . $ext['extension'];

                                                $adapter->setDestination($this->_path_files . DIRECTORY_SEPARATOR . $path);
                                                $adapter->addFilter('Rename', array(
                                                    'source' => $info['tmp_name'],
                                                    'target' => $this->_path_files . DIRECTORY_SEPARATOR . $path . DIRECTORY_SEPARATOR . $file_name,
                                                    'overwrite' => true));
                                                $adapter->receive();

                                                $data = array(); //EXCHANGE_FILE
                                                $data['file_path'] = $this->_path_files . DIRECTORY_SEPARATOR . $path;
                                                $data['file_name'] = $file_name;
                                                $table_exchange_file->update($data, $file_id);

                                                $this->_redirect("/" . $this->controller . "/lot-edit/" . $id . "/id-lot/" . $lot_id);
                                            } else {
                                                @unlink($info['tmp_name']);
                                                $has_error = AuctionController::UPLOAD_ERROR;
                                            }
                                        } else {
                                            @unlink($info['tmp_name']);
                                            $has_error = AuctionController::DB_ERROR;
                                        }
                                    } else {
                                        @unlink($info['tmp_name']);
                                        $has_error = AuctionController::DB_ERROR;
                                    }
                                } else {
                                    @unlink($info['tmp_name']);
                                    $has_error = AuctionController::ERROR_COMPARE_KOATUU;
                                }
                            } else {
                                @unlink($info['tmp_name']);
                                $has_error = AuctionController::ERROR_EXCHANGE_FILE;
                            }
                        } else {
                            @unlink($info['tmp_name']);
                            $has_error = AuctionController::ERROR_FILE_TYPE;
                        }
                    } else {
                        @unlink($info['tmp_name']);
                        $has_error = AuctionController::UPLOAD_ERROR;
                    }
                }
            }
        }

    	if ($has_error) $this->_redirect("/" . $this->controller . "/lots/" . $id . "/error/" . $has_error);
        
        $this->_redirect("/" . $this->controller . "/lots/" . $id);
    }

    public function removeLotAction() {
        $id = intval($this->_request->getParam('id'));
        //if (empty($id)) $this->_redirect('/error/e404');

        $form = new Llib_Form($this->_request);
        $posted_data = $form->GetPostedData();

        if (count($posted_data['selected_id']) > 0)
            $this->_table_lots->remove($posted_data['selected_id'], $this->_user->id);

        if (!empty($id))$this->_redirect("/" . $this->controller . "/lots/" . $id);
        else $this->_redirect("/" . $this->controller . "/lot-list");
    }

    public function viewLotAction() {
        $id = $this->_request->getParam('id',0);
        $id_lot = $this->_request->getParam('id-lot',0);
        $id_auction = ($id > 0) ? $id : $this->_table_lots->getAuctionID($id_lot);
        if (!($id_lot>0)) $this->_redirect('/error/e404');

        $form = new Llib_Form($this->_request);
                
        if ($this->_request->isPost()) {    		
            $posted_data = $form->GetPostedData();
            if(!empty($posted_data)){
	            if(isset($posted_data['id_status'])){                        
                        // чистим лишние поля формы перед обновлением записи в БД
	            	unset($posted_data['id-lot']);
                        unset($posted_data['file_type']);
                        unset($posted_data['file_name']);
                        unset($posted_data['nul']);
                        unset($posted_data['ntp']);
                        // если до начала аукциона меньше 30 дней передача на проверку в ОблЗем не проходит
                        if(($posted_data['id_status'] == 1 && $this->checkDate($posted_data['start_date'])))
                            $form->SetError("Ви не можете передати матеріал на перевірку у зв'язку з тим, що до початку аукціону менше 30 днів");
                        else{// до начала аукциона больше 30 дней - обновляем статус лота
                            unset($posted_data['start_date']);
                            if ($this->_table_lots->update($posted_data, $id_lot, $this->_user->id, $this->_user->role_id)) {
                                    $form->SetSuccess("Статус успішно змінено.");	            		                       
                            }else // если обновление не прошло - лот уже опубликовали - статус = 2 
                                  //(изменение статуса с 2 на 3 невозможно)
                                $form->SetError("Ви не можете повернути матеріал у зв'язку з тим, що його було вже опубліковно");
                        }
	            }else $form->SetError("Ви не змінили статус.");
            }
        }      
        
        $data = $this->_table_lots->getLotInfo($id_lot);
        if($data['is_ghost']) $this->_redirect("/" . $this->controller . "/lots/" . $id_auction);
        
        if($data['id_status'] == 11){
            $table_attaches = new Admin_Table_Auction_Attaches();
            $add_data = $table_attaches->getVideoFile($id_lot);
            $add_data['video_path'] = $this->_http_files . $add_data['video_path'];
            $data = array_merge($data, $add_data);
        }
        
        $data = array_merge($data, $this->_table_lots->getLotFilesCount($id_lot));
        
        if (!empty($data) && $data['id_status_reason']>0 && $data['id_status_reason']<7) 
        	$data['reason'] = $this->_table_lots->getStatusReasons($data['id_status'],$data['id_status_reason']);
        
        if($form->GetError() == 0 && $data['id_status']==AuctionController::STATUS_REJECTED) 
            $form->SetError("Повернуто з причиною: ".$data['reject_reason']);        
        if($form->GetError() == 0 && $data['id_status']>10 && $data['is_approved'] != 1 && $data['id_status'] != 15) 
            $form->SetError("Результати торгів не підтвержено і не опубліковано.");
        if($form->GetError() == 0 && $data['is_gone'] == 1 && $data['id_status'] == 2) 
            $form->SetError("Торги відбулися. Матеріали мають бути надані на протязі 5 робочих днів з ".$data['start_date'].".");

        //первый параметр устанавливает оператора для выборки списка возможных статусов  
        if($this->_user->role_id == AuctionController::CENTER_USER){
            $role = AuctionController::CENTER_USER;
        }else{
            $role = 0;
        }
        $data['status_list'] = $this->_table_lots->GetStatusListForChange($role, @$data['id_status']);
      
        
        $form->AddData($data);

        $this->startContent();
        $this->view->xmlWriter->startElement("Main");
        $this->view->xmlWriter->writeAttribute('id', $id_auction);
        $this->view->xmlWriter->writeAttribute('id_lot', $id_lot);
        $this->view->xmlWriter->writeAttribute('id_auction', $id_auction);
        $this->view->assign($form->GetFrom());
        $this->view->xmlWriter->endElement();
        $this->view->xmlWriter->endElement();
    }

    public function lotEditAction() {
        $id = $this->_request->getParam('id',0);
        $id_lot = $this->_request->getParam('id-lot',0);
        $id_auction = $this->_table_lots->getAuctionID($id_lot);
        if (!($id_lot>0)) $this->_redirect('/error/e404');

        $saveexit = $this->_getParam('saveexit');
        $form = new Llib_Form($this->_request);

        if ($this->_request->isPost()) {
            $posted_data = $form->GetPostedData();

            if ($this->_table_lots->updateLot($posted_data, $id_lot, $this->_user->id)) {
                if (!is_null($saveexit)) $this->_redirect("/" . $this->controller . "/view-lot/" . $id . "/id-lot/" . $id_lot);
                $form->SetSuccess();
            } else $form->SetError($this->_table->GetError());
        }

        $data = $this->_table_lots->getDataRow($id_lot);
        if($data['id_status'] == AuctionController::STATUS_REJECTED) $form->SetError("Повернуто з причиною: ".$data['reject_reason']);
        if($data['id_status']>0 && $data['id_status']!=3 && $this->_user->role_id != AuctionController::CENTER_USER) 
            $this->_redirect('/'.$this->controller.'/view-lot/'.$id.'/id-lot/'.$id_lot);

        $form->AddData($data);

        $this->startContent();
        $this->view->xmlWriter->startElement("Main");
        $this->view->xmlWriter->writeAttribute('id', $id);
        $this->view->xmlWriter->writeAttribute('id_lot', $id_lot);
        $this->view->xmlWriter->writeAttribute('id_auction', $id_auction);    
           
        $this->view->assign($form->GetFrom());
        $this->view->xmlWriter->endElement();
        $this->view->xmlWriter->endElement();
    }

	public function lotHistoryAction() {
        $id = $this->_request->getParam('id',0);
        $id_lot = $this->_request->getParam('id-lot',0);
        $id_auction = $this->_table_lots->getAuctionID($id_lot);
        if (!($id_lot>0)) $this->_redirect('/error/e404');

        $table_history = new Admin_Table_Auction_LotHistory();

        $lclm = new Llib_List($this->_request, $this->_sess);
        $lclm->AddParams(array(
            'checkboxes' => false,
        	'link_fields'=>array('file_name'),
            'link' => "/" . $this->controller . "/lot-history/" . $id . "/lot/" . $id_lot . "/"
        ));
        $lclm->AddColumn('Дата', 'add_date', array('width' => '5%', 'sort' => 1));
        $lclm->AddColumn('Користувач', 'user', array('width' => '20%', 'sort' => 0));
        $lclm->AddColumn('Коментар', 'comment', array('width' => '20%', 'sort' => 0));
        $lclm->AddColumn('На статус', 'status', array('width' => '20%', 'sort' => 0));
        $lclm->AddColumn('З причиною', 'reason', array('width' => '35%', 'sort' => 0));
        $lclm->AddData($table_history->getDataList($lclm->page, $lclm->s, $lclm->pager_count, array('id_lot'=>$id_lot)));

        $this->startContent();
        $this->view->xmlWriter->startElement("Main");
        $this->view->xmlWriter->writeAttribute('id', $id);
        $this->view->xmlWriter->writeAttribute('id_lot', $id_lot);
        $this->view->xmlWriter->writeAttribute('id_auction', $id_auction);
        $this->view->assign('List', $lclm->GetList());
        $this->view->xmlWriter->endElement();
        $this->view->xmlWriter->endElement();
    }
    
    public function auctionHistoryAction() {
        $id = $this->_request->getParam('id',0);
        
        if (!($id>0)) $this->_redirect('/error/e404');

        $table_history = new Admin_Table_Auction_LotHistory();

        $lclm = new Llib_List($this->_request, $this->_sess);
        $lclm->AddParams(array(
            'checkboxes' => false,
        	'link_fields'=>array('file_name'),
            'link' => "/" . $this->controller . "/lot-history/" . $id . "/"
        ));
        $lclm->AddColumn('Дата', 'add_date', array('width' => '5%', 'sort' => 1));
        $lclm->AddColumn('Користувач', 'user', array('width' => '20%', 'sort' => 0));
        $lclm->AddColumn('Коментар', 'comment', array('width' => '20%', 'sort' => 0));
        $lclm->AddColumn('На статус', 'status', array('width' => '20%', 'sort' => 0));
        $lclm->AddColumn('З причиною', 'reason', array('width' => '35%', 'sort' => 0));
        $lclm->AddData($table_history->getDataList($lclm->page, $lclm->s, $lclm->pager_count, array('id_lot'=>'0', 'id_auction'=>$id)));

        $this->startContent();
        $this->view->xmlWriter->startElement("Main");
        $this->view->xmlWriter->writeAttribute('id', $id);
        $this->view->assign('List', $lclm->GetList());
        $this->view->xmlWriter->endElement();
        $this->view->xmlWriter->endElement();
    }
    
    public function fileAttacheAction() {
 
        
        $id = $this->_request->getParam('id',0);
        $id_lot = $this->_request->getParam('id-lot',0);
        $id_auction = $this->_table_lots->getAuctionID($id_lot);
        if (!($id_lot>0)) $this->_redirect('/error/e404');

        $filters = array();

        if ($this->_request->isPost()) $filters['by_file_type'] = $this->_request->getParam('by_file_type', '');

        $filters = $this->SessionVarsEx($filters, array('by_file_type'), $this->_request->getParam('reset', false));

        $table_attaches = new Admin_Table_Auction_Attaches();
        $form = new Llib_Form($this->_request);
        $data['id_status_auction'] = $this->_table->getStatus($id_auction);
        $data_lot = $this->_table_lots->getLotInfo($id_lot);
        $data['id_status'] = $data_lot['id_status'];
        unset($data_lot);
        $data['attache_types'] = $table_attaches->getFileTypes();
        $data = array_merge($data, $table_attaches->getLotFilesCount($id_lot));
        $data = array_merge($data, $filters);
        $form->AddData($data);

        $lclm = new Llib_List($this->_request, $this->_sess);
        $lclm->AddParams(array(
            'checkboxes' => true,
        	//'link_fields'=>array('file_name'),
            'link' => "/" . $this->controller . "/download/" . $id . "/lot/" . $id_lot . "/attache/"
        ));
        $lclm->AddColumn('Ім\'я файлу', 'file_name', array('width' => '30%', 'sort' => 1));
        $lclm->AddColumn('Тип файлу', 'file_type', array('width' => '70%', 'sort' => 1));
        $lclm->AddData($table_attaches->getDataList($id_lot, $lclm->page, $lclm->s, $lclm->pager_count, $filters));

        $this->startContent();
        $this->view->xmlWriter->startElement("Main");
        
        $this->view->xmlWriter->writeAttribute('id', $id);
        $this->view->xmlWriter->writeAttribute('id_lot', $id_lot);
        $this->view->xmlWriter->writeAttribute('id_auction', $id_auction);
        $this->view->assign('List', $lclm->GetList());
        $this->view->assign($form->GetFrom());
         
         
         
        $this->view->xmlWriter->endElement();
        $this->view->xmlWriter->endElement();  
    }

    public function downloadAction() {
        $id = intval($this->_request->getParam('id'));
        $lot_id = intval($this->_request->getParam('lot'));
        $attache_id = intval($this->_request->getParam('attache'));

        if (empty($id) || empty($lot_id) || empty($attache_id)) $this->_redirect('/error/e404');

        $table_attaches = new Admin_Table_Auction_Attaches();
        $file_data = $table_attaches->getFileData($attache_id);

        if (empty($file_data)) $this->_redirect('/error/e404');

        $this->downloadAttachment($this->_path_files . $file_data['file_path'] . DIRECTORY_SEPARATOR . $file_data['file_name'], $file_data['name']);
        $this->_redirect("/" . $this->controller . "/file-attache/" . $id . "/id-lot/" . $lot_id);
    }

    private function downloadAttachment($path, $name) {
        ignore_user_abort(true);
        set_time_limit(0);

        if (file_exists($path)) {
            if (preg_match('/Opera(\| )([0-9].[0-9]{1,2})/', $_SERVER['HTTP_USER_AGENT']))
                $UserBrowser = "Opera";
            elseif (preg_match('/MSIE ([0-9].[0-9]{1,2})/', $_SERVER['HTTP_USER_AGENT']))
                $UserBrowser = "IE";
            else
                $UserBrowser = "";

            $mime_type = ($UserBrowser == 'IE' || $UserBrowser == 'Opera') ? 'application/octetstream' : 'application/octet-stream';
            @ob_end_clean();

            header('Content-Type: ' . $mime_type);
            header('Content-Disposition: attachment; filename="' . $name . '"');
            header('Accept-Ranges: bytes');
            header("Cache-control: private");
            header('Pragma: private');
            header("Content-Length: " . filesize($path));

            $fd = fopen($path, "r");
            if ($fd) {
                while (!feof($fd)) {
                    $buffer = fread($fd, 1024 * 128);
                    echo $buffer;
                }
                @ob_flush();
                fclose($fd);
            }
        }
    }

    public function removeAttacheAction() {
        $id = intval($this->_request->getParam('id'));
        $id_lot = intval($this->_request->getParam('id-lot'));

        if (empty($id) || empty($id_lot)) $this->_redirect('/error/e404');

        $form = new Llib_Form($this->_request);
        $posted_data = $form->GetPostedData();

        $table_attaches = new Admin_Table_Auction_Attaches();

        if (count($posted_data['selected_id']) > 0)
            $table_attaches->remove($posted_data['selected_id'], $this->_user->id);

        $this->_redirect("/" . $this->controller . "/file-attache/" . $id . "/id-lot/" . $id_lot);
    }

    public function addAttacheAction_old() {
        $id = intval($this->_request->getParam('id'));
        $id_lot = intval($this->_request->getParam('id-lot'));
        $file_type = intval($this->_request->getParam('file_type'));

        if (empty($id) || empty($id_lot)) $this->_redirect('/error/e404');

        $form = new Llib_Form($this->_request);

        $result = array(
            'success' => true,
            'msg' => ""
        );

        if ($this->_request->isPost()) {
            $posted_data = $form->GetPostedData();
            
            if (!empty($posted_data)) {
                $adapter = $this->getFileAdapterAll();
                
                if ($adapter->receive()) {
                    $result['stage'] = 01;
                    $files = $adapter->getFileInfo();
                    
//                    if (!empty($files)) {
//                        $result['stage'] = 1;
                        foreach ($files as $file => $info) {
                            //print_r($adapter->isUploaded($file));die();
                            if ($adapter->isUploaded($file)/* && $adapter->isValid($file)*/) {
                                $result['stage'] = 21;
                                $data = array(); // ATTACHES
                                $data['name'] = $info['name'];
                                $data['id_lot'] = $id_lot;
                                $data['type'] = $file_type;

                                $table_attaches = new Admin_Table_Auction_Attaches();
                                $file_id = $table_attaches->insert($data, $this->_user->id);

                                if ($file_id > 0) {
                                    $result['stage'] = 31;
                                    $path = "attaches" . DIRECTORY_SEPARATOR . intval($file_id / 1000000) . DIRECTORY_SEPARATOR . intval($file_id / 1000) . DIRECTORY_SEPARATOR . $id;
                                    if ($this->_files->CreateFolderRecursive($path)) {
                                        $result['stage'] = 41;
                                        $ext = pathinfo($info['name']);
                                        $file_name = $file_id . "." . $ext['extension'];

                                        $adapter->setDestination($this->_path_files . DIRECTORY_SEPARATOR . $path);
                                        $adapter->addFilter('Rename', array(
                                            'source' => $info['tmp_name'],
                                            'target' => $this->_path_files . DIRECTORY_SEPARATOR . $path . DIRECTORY_SEPARATOR . $file_name,
                                            'overwrite' => true));
                                        //try { 
                                            //$adapter->receive();
                                            $result['stage'] = 51;
                                            $data = array(); // ATTACHES
                                            $data['file_path'] = DIRECTORY_SEPARATOR . $path;//$this->_path_files . 
                                            $data['file_name'] = $file_name;
                                            $table_attaches->update($data, $file_id);
                                        //} catch (Zend_File_Transfer_Exception $e) { 
//                                            print_r($e->getMessage());die();
//                                            $result['stage'] = 50;
//                                            @unlink($info['tmp_name']);
//                                            $result['success'] = false;
//                                            $result['msg'] = implode("\n", $adapter->getMessages());
//                                            $result['msg'] = $result['msg'] + ' !!! ' +VAR_DUMP($file)+ '!!!!';
//                                        } 
//                                        if (!$adapter->receive()) {//$adapter->receive();
//                                            print_r('_'.$adapter->getMessages().'_');die();
//                                            $result['stage'] = 50;
//                                            @unlink($info['tmp_name']);
//                                            $result['success'] = false;
//                                            $result['msg'] = implode("\n", $adapter->getMessages());
//                                            $result['msg'] = $result['msg'] + ' !!! ' +VAR_DUMP($file)+ '!!!!';
//
//                                        }
//                                        else{
//                                            $result['stage'] = 51;
//                                            $data = array(); // ATTACHES
//                                            $data['file_path'] = DIRECTORY_SEPARATOR . $path;//$this->_path_files . 
//                                            $data['file_name'] = $file_name;
//                                            $table_attaches->update($data, $file_id);
//                                        }
                                    } else {
                                        @unlink($info['tmp_name']);
                                        $result['stage'] = 40;
                                        $result['success'] = false;
                                        $result['msg'] = "Недостатньо прав доступу до файлової системи.";
                                    }
                                } else {
                                    @unlink($info['tmp_name']);
                                    $result['stage'] = 30;
                                    $result['success'] = false;
                                    $result['msg'] = "Виникла помилка бази даних.";
                                }
                            } else {    
                                @unlink($info['tmp_name']);
                                $result['stage'] = 20;
                                $result['success'] = false;
                                $result['msg'] = implode("\n", $adapter->getMessages());//"Не вірний формат файлу.";
                            }
                        }
//                    } else {
//                        $result['stage'] = 10;
//                        $result['success'] = false;
//                        $result['msg'] = "Перевищено допустимий розмір файлу.";
//                    }
                } else {
                    $result['stage'] = 00;
                    $result['success'] = false;
                    $result['msg'] = 'Виникла помилка під час завантаження обмінного файлу.(' . implode("\n", $adapter->getMessages()) . ').Спробуйте ще раз.';
                }
            }
        }

        echo Zend_Json::encode($result);
        die();
    }
    
    public function addAttacheAction() {
        $id = intval($this->_request->getParam('id'));
        $id_lot = intval($this->_request->getParam('id-lot'));
        $file_type = intval($this->_request->getParam('file_type'));

        if (empty($id) || empty($id_lot)) $this->_redirect('/error/e404');

        $form = new Llib_Form($this->_request);

        $result = array(
            'success' => true,
            'msg' => ""
        );

        if ($this->_request->isPost()) {
            $posted_data = $form->GetPostedData();
            
            if (!empty($posted_data)) {
                $adapter = $this->getFileAdapterAll();
                
                if ($adapter->receive()) {
                        $result['stage'] = 01;
                        $files = $adapter->getFileInfo();
                        foreach ($files as $file => $info) {
                                $data = array();
                                $table_attaches = new Admin_Table_Auction_Attaches();
                                $file_id = $table_attaches->insert($data, $this->_user->id);
                                $path = "attaches" . DIRECTORY_SEPARATOR . intval($file_id / 1000000) . DIRECTORY_SEPARATOR . intval($file_id / 1000) . DIRECTORY_SEPARATOR . $id;
                                if ($this->_files->CreateFolderRecursive($path)){
                                        $result['stage'] = 41;
                                        $ext = pathinfo($info['name']);
                                        $file_name = $file_id . "." . $ext['extension'];

                                        if (rename($info['tmp_name'], $this->_path_files . DIRECTORY_SEPARATOR . $path . DIRECTORY_SEPARATOR . $file_name)) {
                                                $result['stage'] = 21;                                                
                                                if ($file_id > 0) {
                                                    $data['name'] = $info['name'];
                                                    $data['id_lot'] = $id_lot;
                                                    $data['type'] = $file_type;
                                                    $data['file_path'] = DIRECTORY_SEPARATOR . $path;//$this->_path_files . 
                                                    $data['file_name'] = $file_name;
                                                    $table_attaches->update($data, $file_id);

                                                } else {
                                                    @unlink($info['tmp_name']);
                                                    $result['stage'] = 30;
                                                    $result['success'] = false;
                                                    $result['msg'] = "Виникла помилка бази даних.";
                                                }
                                        } else {    
                                            @unlink($info['tmp_name']);
                                            if ($file_id > 0) $table_attaches->remove(array($file_id), $this->_user->id);
                                            $result['stage'] = 20;
                                            $result['success'] = false;
                                            $result['msg'] = implode("\n", "Недостатньо прав доступу до файлової системи(зміна ім\'я файлу)");//"Не вірний формат файлу.";
                                        }
                                } else {
                                    @unlink($info['tmp_name']);
                                    if ($file_id > 0) $table_attaches->remove(array($file_id), $this->_user->id);
                                    $result['stage'] = 40;
                                    $result['success'] = false;
                                    $result['msg'] = "Недостатньо прав доступу до файлової системи.";
                                }
                        }
                } else {
                    $result['stage'] = 00;
                    $result['success'] = false;
                    $result['msg'] = 'Виникла помилка під час завантаження обмінного файлу.(' . implode("\n", $adapter->getMessages()) . ').Спробуйте ще раз.';
                }
            }
        }

        echo Zend_Json::encode($result);
        die();
    }

    public function removeAction() {
        $form = new Llib_Form($this->_request);
        $posted_data = $form->GetPostedData();

        if (count($posted_data['selected_id']) > 0)
            $this->_table->remove($posted_data['selected_id'], $this->_user->id);

        $this->_redirect("/" . $this->controller);
    }

    public function ajaxDistrictsReloadAction() {
        $id_region = intval(@$_REQUEST['id_region']);

        echo "<option value='0'>-- Не вказано --</option>";

        if (is_numeric($id_region) && !empty($id_region)) {
            $items = $this->_table->addressGetDistricts($id_region);

            if (!empty($items) && is_array($items)) {
                foreach ($items as $value)
                    echo sprintf("<option value='%d'>%s</option>", $value['id'], $value['name']);
            }
        }

        die();
    }

    public function ajaxTownReloadAction() {
        $id_region = intval(@$_REQUEST['id_region']);
        $id_district = intval(@$_REQUEST['id_district']);

        echo "<option value='0'>-- Не вказано --</option>";

        if (is_numeric($id_region) && !empty($id_region) && is_numeric($id_district) && !empty($id_district)) {
            $items = $this->_table->addressGetTowns($id_region, $id_district);

            if (!empty($items) && is_array($items)) {
                foreach ($items as $value)
                    echo sprintf("<option value='%d'>%s</option>", $value['id'], $value['name']);
            }
        }

        die();
    }
    private function checkDate($start_date, $format='%r%a'){
        $return = true;
        
        $today = new DateTime("now");        
        $date = new DateTime($start_date);
	$interval = $today->diff($date);
        $res = $interval->format($format);
        
        if ($res > 30) $return = false;
        
        return $return;
    }

}
